import { ElMessage, ElLoading } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import 'element-plus/theme-chalk/el-loading.css'
import { useUserStore } from "@/stores/user.js"
import router from "@/router"
// axios基础配置
import axios from "axios";
const httpIntance = axios.create({
  baseURL: "http://pcapi-xiaotuxian-front-devtest.itheima.net",
  timeout: 10000
})
let loading = null
// 请求拦截器
httpIntance.interceptors.request.use(config => {
  const userStore = useUserStore()
  loading = ElLoading.service({
    lock: true,
    text: '页面加载中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  const { token } = userStore.userInfo
  if (token) {
    // 模式
    config.headers.Authorization = `Bearer ${token}`
  }
  // else{
  //   userStore.clearUserInfo()
  //   router.push({ path: "/login" })
  // }
  return config
}, e => Promise.reject(e))

// axios响应式拦截器
httpIntance.interceptors.response.use(res => {
  loading.close()
  return res.data
}, e => {
  const userStore = useUserStore()
  // // 统一错误提示
  ElMessage({
    type: "error",
    message: e?.response?.data?.message
  })
  // 401token验证失效
  // 1.清除本地数据
  if (e?.response?.status === 401) {
    loading.close()
    userStore.clearUserInfo()
    router.push({ path: "/login" })
  }
  // 2.跳转到登陆页
  return Promise.reject(e)
})

export default httpIntance